package com.stylefeng.guns.modular.flagglory.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.persistence.model.Question;
import com.stylefeng.guns.common.persistence.model.QuestionCategory;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.util.PoiUtil;
import com.stylefeng.guns.modular.flagglory.service.IQuestionCategoryService;
import com.stylefeng.guns.modular.flagglory.service.IQuestionService;
import com.stylefeng.guns.modular.flagglory.warpper.QuestionWarpper;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.export.ExcelExportServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 题库控制器
 *
 * @author fengshuonan
 * @Date 2018-01-30 09:37:43
 */
@Controller
@RequestMapping("/question")
public class QuestionController extends BaseController {

    private String PREFIX = "/flagGlory/question/";

    @Autowired
    private IQuestionService questionService;

    @Autowired
    private IQuestionCategoryService questionCategoryService;

    /**
     * 跳转到题首页
     */
    @RequestMapping("")
    public String index(Model model) {
        List<QuestionCategory> questionCategories = questionCategoryService.selectList(null);
        model.addAttribute("questionCategories", questionCategories);
        return PREFIX + "question.html";
    }

    /**
     * 跳转到添加题
     */
    @RequestMapping("/question_add")
    public String questionAdd() {
        return PREFIX + "question_add.html";
    }

    /**
     * 跳转到修改题
     */
    @RequestMapping("/question_update/{questionId}")
    public String questionUpdate(@PathVariable Integer questionId, Model model) {
        Question question = questionService.selectById(questionId);
        model.addAttribute("item", question);
        Integer categoryid = question.getCategoryid();
        QuestionCategory questionCategory = questionCategoryService.selectById(categoryid);
        if (null != questionCategory) {
            model.addAttribute("categoryName", questionCategory.getName());
        } else {
            model.addAttribute("categoryName", "无");
        }
        JSONObject info = JSON.parseObject(question.getInfo());
        model.addAttribute("info", info);
        LogObjectHolder.me().set(question);
        return PREFIX + "question_edit.html";
    }

    /**
     * 获取题列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Integer categoryId, Integer limit, Integer pageNum, String order) {
        EntityWrapper<Question> entityWrapper = new EntityWrapper<>();
        Page<Map<String, Object>> mapPage = questionService.selectMapsPage(new Page<>(pageNum, limit), entityWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        int total = questionService.selectCount(entityWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", super.warpObject(new QuestionWarpper(records)));
        result.put("total", total);
        return result;
    }

    /**
     * 新增题
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@Valid Question question, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new Exception(result.getFieldError().getDefaultMessage());
        }
        questionService.insert(question);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除题
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer questionId) {
        questionService.deleteById(questionId);
        return SUCCESS_TIP;
    }

    /**
     * 修改题
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(@Valid Question question, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new Exception(result.getFieldError().getDefaultMessage());
        }
        questionService.updateById(question);
        return super.SUCCESS_TIP;
    }

    /**
     * 题详情
     */
    @RequestMapping(value = "/detail/{questionId}")
    @ResponseBody
    public Object detail(@PathVariable("questionId") Integer questionId) {
        return questionService.selectById(questionId);
    }

    @RequestMapping("/goImport")
    public String goImport() {
        return PREFIX + "import.html";
    }

    @RequestMapping("/doImport")
    @ResponseBody
    public Object doImport(@RequestParam("file") MultipartFile file) throws Exception {
        List<QuestionCategory> questionCategories = questionCategoryService.selectList(null);
        List<Question> questions = new ArrayList<>();
        ImportParams params = new ImportParams();
        //设置最大sheet
        params.setSheetNum(5);
        List<Map<String, Object>> list = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);
        JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(list));
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                JSONObject json = jsonArray.getJSONObject(i);
                Question question = new Question();
                String questionCategoryName = json.getString("题目类型");
                for (QuestionCategory questionCategory : questionCategories) {
                    if (questionCategory.getName().equals(questionCategoryName)) {
                        question.setCategoryid(questionCategory.getId());
                        break;
                    }
                }
                String infoText = json.getString("题目");
                //答案集合
                JSONArray answers = new JSONArray();
                String answer1 = json.getString("选项一");
                String answer2 = json.getString("选项二");
                String answer3 = json.getString("选项三");
                String answer4 = json.getString("选项四");
                String remarks = json.getString("备注");
                Integer rightAnswer = null;
                try {
                    //正确答案为数组下标 -1
                    rightAnswer = json.getInteger("答案") - 1;
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                if (StringUtils.isBlank(infoText) || infoText.length() > 120) {
                    continue;
                }
                jsonObject.put("infoText", infoText);
                if (StringUtils.isNotBlank(answer1) && answer1.length() <= 10) {
                    answers.add(answer1);
                } else {
                    continue;
                }
                if (StringUtils.isNotBlank(answer2) && answer2.length() <= 10) {
                    answers.add(answer2);
                } else {
                    continue;
                }
                if (StringUtils.isNotBlank(answer3) && answer3.length() <= 10) {
                    answers.add(answer3);
                } else {
                    continue;
                }
                if (StringUtils.isNotBlank(answer4) && answer4.length() <= 10) {
                    answers.add(answer4);
                } else {
                    continue;
                }
                jsonObject.put("answers", answers);
                jsonObject.put("rightAnswer", rightAnswer);
                question.setInfo(jsonObject.toJSONString());
                if (StringUtils.isNotBlank(remarks)) {
                    question.setRemarks(remarks);
                }
                Integer degree = json.getInteger("难度");
                question.setDegree(degree);
                questions.add(question);
            } catch (Exception e) {
                continue;
            }
        }
        if (questionService.insertBatch(questions)) {
            return SUCCESS_TIP;
        } else {
            throw new Exception("导入失败");
        }
    }

    @RequestMapping("/doExport")
    public void doExport(HttpServletRequest request, HttpServletResponse response) {
        List<QuestionCategory> questionCategories = questionCategoryService.selectList(null);
        List<Map<String, Object>> mapList = new ArrayList<>();
        String[] hdNames = new String[]{"题目", "答案", "选项一", "选项二", "选项三", "选项四", "题目类型", "备注"};
        String[] hds = new String[]{"infoText", "rightAnswer", "0", "1", "2", "3", "categoryName", "remarks"};
        for (QuestionCategory category : questionCategories) {
            Map<String, Object> map = new HashMap<>();
            EntityWrapper<Question> entityWrapper = new EntityWrapper<>();
            entityWrapper.where("categoryid=" + category.getId());
            List<Question> questions = questionService.selectList(entityWrapper);
            JSONArray dataArray = new JSONArray();
            for (Question question : questions) {
                String info = question.getInfo();
                JSONObject data = new JSONObject();
                JSONObject jsonObject = JSONObject.parseObject(info);
                data.put("infoText", jsonObject.getString("infoText"));
                data.put("rightAnswer", jsonObject.getInteger("rightAnswer") + 1);
                data.put("remarks", question.getRemarks());
                data.put("categoryName", category.getName());
                JSONArray answers = jsonObject.getJSONArray("answers");
                for (int i = 0; i < answers.size(); i++) {
                    data.put(i + "", answers.getString(i));
                }
                data.put("4", data.getOrDefault("4", ""));
                dataArray.add(data);
            }
            map.put("hdNames", hdNames);
            map.put("hds", hds);
            map.put("data", dataArray);
            map.put("sheetName", category.getName());
            mapList.add(map);
        }
        try {
            PoiUtil.outPutExcels(mapList, "题库信息", request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
